package com.joker.web.controller.orange;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.joker.common.annotation.RepeatSubmit;
import com.joker.common.core.controller.BaseController;
import com.joker.common.core.domain.PageQuery;
import com.joker.common.core.domain.R;
import com.joker.common.core.page.TableDataInfo;
import com.joker.common.helper.LoginHelper;
import com.joker.orange.domain.CollectionInfo;
import com.joker.orange.domain.RedemptionCode;
import com.joker.orange.domain.bo.*;
import com.joker.orange.domain.vo.*;
import com.joker.orange.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 个人中心相关
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/personal/center")
public class AppPersonalCenterController extends BaseController {

    private final IUserInfoService userInfoService;
    private final IMemberInfoService memberInfoService;
    private final IDiamondConsumeRecordService diamondConsumeRecordService;
    private final IDiamondRechargeService diamondRechargeService;
    private final ICollectionService collectionService;
    private final PublicService publicService;
    private final ICommentService commentService;
    private final IPlayRecordService playRecordService;
    private final IApplicationCenterService applicationCenterService;
    private final IVideoInfoService videoInfoService;
    private final INovelInfoService novelInfoService;
    private final ICaricatureInfoService caricatureInfoService;
    private final IUserLikeService userLikeService;
    private final IBuyOrderService buyOrderService;
    private final AppPersonalCenterService personalCenterService;

    /**
     * 充值会员列表
     */
    @PostMapping("/selectMemberInfoList")
    public R<List<MemberInfoVo>> selectMemberInfoList(@RequestBody MemberInfoBo memberInfoBo) {
        return R.ok(memberInfoService.queryList(memberInfoBo));
    }

    /**
     * 会员购买记录
     */
    @PostMapping("/selectMemberOrderList")
    public TableDataInfo<MemberOrderVo> selectMemberOrderList(@RequestBody JSONObject jsonObject){
        return personalCenterService.queryOrderList(jsonObject.getInt("pageNum"), jsonObject.getInt("pageSize"));
    }

    /**
     * 充值钻石列表
     */
    @PostMapping("/selectDiamondRechargeList")
    public R<List<DiamondRechargeVo>> selectDiamondRechargeList() {
        return R.ok(diamondRechargeService.queryList(new DiamondRechargeBo()));
    }

    /**
     * 钻石消费记录
     */
    @PostMapping("/selectUserDiamondConsumeRecordList")
    public TableDataInfo<DiamondConsumeRecordVo> selectUserDiamondConsumeRecordList(@RequestBody DiamondConsumeRecordBo diamondConsumeRecordBo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(diamondConsumeRecordBo.getPageNum());
        pageQuery.setPageSize(diamondConsumeRecordBo.getPageSize());
        return diamondConsumeRecordService.queryPageList(diamondConsumeRecordBo, pageQuery);
    }

    /**
     * 分享邀请
     */
    @PostMapping("/shareInvitation")
    public R<Map<String, Object>> shareInvitation() {
        Map<String, Object> result = new HashMap<>();
        Long userId = LoginHelper.getUserId();
        UserInfoVo userInfo = userInfoService.queryById(userId);
        result.put("inviteCode", userInfo.getInviteCode());
        result.put("qrCode", publicService.getQrCode("https://www.baidu.com", userInfo.getInviteCode()));
        return R.ok(result);
    }

    /**
     * 我的收藏
     */
    @PostMapping("/selectPageCollectionList")
    public TableDataInfo<CollectionVo> selectPageCollectionList(@RequestBody CollectionBo collectionBo) {
        collectionBo.setUserId(LoginHelper.getUserId());
        TableDataInfo<CollectionVo> pageList = null;
        // 0-网格视频、1-短视频、2-小说、3-漫画、4-动漫
        switch (collectionBo.getCollectionType()) {
            case "0":
                // 当 collectionType 为 "0" 时的逻辑
                pageList = collectionService.selectCollectionByLongVideo(collectionBo);
                break;
            case "1":
                // 当 collectionType 为 "1" 时的逻辑
                pageList = collectionService.selectCollectionByShortVideo(collectionBo);
                break;
            case "2":
                // 当 collectionType 为 "2" 时的逻辑
                pageList = collectionService.selectCollectionByNovel(collectionBo);
                break;
            case "3":
                // 当 collectionType 为 "3" 时的逻辑
                pageList = collectionService.selectCollectionByCaricature(collectionBo);
                break;
            default:
                // 其他情况的逻辑
                pageList = collectionService.selectCollectionByAnime(collectionBo);
                break;
        }

        return pageList;
    }

    /**
     * 批量删除收藏
     */
    @PostMapping("/deleteCollection")
    public R<Void> deleteCollection(@RequestBody JSONObject jsonObject) {
        if (!jsonObject.containsKey("ids") || ObjectUtil.isEmpty(jsonObject.get("ids"))) {
            return R.fail("收藏ID不能为空！");
        }
        List<String> collectionIds = Arrays.asList(jsonObject.getStr("ids").split(","));
        collectionService.deleteCollection(collectionIds);
        return R.ok();
    }

    /**
     * 评论列表
     */
    @PostMapping("/selectPageCommentList")
    public TableDataInfo<CommentVo> selectPageCommentList(@RequestBody CommentBo bo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        bo.setAuditStatus("1");
        bo.setUserId(LoginHelper.getUserId());
        return commentService.queryPageList(bo, pageQuery);
    }

    /**
     * 兑换记录
     */
    @PostMapping("/selectRedemptionCodeList")
    public R<List<RedemptionCode>> selectRedemptionCodeList() {
        return R.ok(personalCenterService.getRedemptionCodeList());
    }

    /**
     * 兑换
     */
    @PostMapping("/updateRedemptionCode")
    public R<Void> updateRedemptionCode(@RequestBody JSONObject jsonObject) {
        if (!jsonObject.containsKey("codeName") || ObjectUtil.isEmpty(jsonObject.get("codeName"))) {
            return R.fail("兑换码不能为空");
        }
        personalCenterService.updateRedemptionCode(jsonObject.getStr("codeName"));
        return R.ok();
    }

    /**
     * 我的购买
     */
    @PostMapping("/selectBuyOrderList")
    public TableDataInfo<BuyOrderVo> selectBuyOrderList(@Validated @RequestBody QueryBuyOrderBo queryBuyOrderBo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(queryBuyOrderBo.getPageNum());
        pageQuery.setPageSize(queryBuyOrderBo.getPageSize());
        BuyOrderBo bo = new BuyOrderBo();
        bo.setUserId(LoginHelper.getUserId());
        bo.setOrderType(queryBuyOrderBo.getOrderType());
        bo.setOrderStatus("1");
        return buyOrderService.queryPageList(bo, pageQuery);
    }

    /**
     * 播放记录
     */
    @PostMapping("/selectPlayRecordList")
    public TableDataInfo<PlayRecordVo> selectPlayRecordList(@RequestBody PlayRecordBo bo) {
        PageQuery pageQuery = new PageQuery();
        pageQuery.setPageNum(bo.getPageNum());
        pageQuery.setPageSize(bo.getPageSize());
        return playRecordService.queryPageList(bo, pageQuery);
    }

    /**
     * 删除播放记录
     */
    @PostMapping("/deletePlayRecord")
    public R<Void> deletePlayRecord(@RequestBody PlayRecordBo bo) {
        playRecordService.deleteWithValidByIds(bo.getIds());
        return R.ok();
    }

    /**
     * 账户凭证
     */
    @PostMapping("/selectAccountVoucher")
    public R<Map<String, Object>> selectAccountVoucher() {
        Map<String, Object> result = new HashMap<>();
        Long userId = LoginHelper.getUserId();
        UserInfoVo userInfo = userInfoService.queryById(userId);
        result.put("qrCode", publicService.getQrCode("https://www.baidu.com", userInfo.getInviteCode()));
        return R.ok(result);
    }

    /**
     * 应用中心
     */
    @PostMapping("/selectApplicationCenterList")
    public TableDataInfo<ApplicationCenterVo> selectApplicationCenterList(@RequestBody PageQuery pageQuery) {
        ApplicationCenterBo bo = new ApplicationCenterBo();
        bo.setIsDisplay("0");
        return applicationCenterService.queryPageList(bo, pageQuery);
    }

    /**
     * 新增点赞/取消点赞
     * likeType 点赞类型（0-网格视频、1-短视频、2-小说、3-漫画、4-动漫）
     * likeTypeId 点赞类型ID
     */
    @PostMapping("/insertOrDeleteLike")
    public R<Void> insertOrDeleteLike(@RequestBody UserLikeBo userLikeBo) {
        log.info("新增点赞/取消点赞入参【insertOrDeleteLike】：{}", JSONUtil.parse(userLikeBo));
        // 有点赞数据，取消点赞，减少点赞次数
        userLikeBo.setUserId(LoginHelper.getUserId());
        UserLikeVo likeVo = userLikeService.queryUserLikeVo(userLikeBo);
        if (ObjectUtil.isNotEmpty(likeVo)) {
            userLikeService.deleteWithValidByIds(Collections.singleton(likeVo.getId()), false);
            if ("2".equals(userLikeBo.getLikeType())) {
                NovelInfoVo novelInfoVo = novelInfoService.queryById(userLikeBo.getLikeTypeId());
                NovelInfoBo novelInfoBo = new NovelInfoBo();
                novelInfoBo.setId(novelInfoVo.getId());
                novelInfoBo.setLikeNum(novelInfoVo.getLikeNum() - 1);
                novelInfoService.updateByBo(novelInfoBo);
            } else if ("3".equals(userLikeBo.getLikeType())) {
                CaricatureInfoVo caricatureInfoVo = caricatureInfoService.queryById(userLikeBo.getLikeTypeId());
                CaricatureInfoBo caricatureInfoBo = new CaricatureInfoBo();
                caricatureInfoBo.setId(caricatureInfoVo.getId());
                caricatureInfoBo.setLikeNum(caricatureInfoVo.getLikeNum() - 1);
                caricatureInfoService.updateByBo(caricatureInfoBo);
            } else {
                VideoInfoVo videoInfoVo = videoInfoService.queryById(userLikeBo.getLikeTypeId());
                VideoInfoBo videoInfoBo = new VideoInfoBo();
                videoInfoBo.setId(videoInfoVo.getId());
                videoInfoBo.setLikeNum(videoInfoVo.getLikeNum() - 1);
                videoInfoService.updateByBo(videoInfoBo);
            }
            return R.ok();
        }
        userLikeBo.setUserId(LoginHelper.getUserId());
        userLikeService.insertByBo(userLikeBo);
        if ("2".equals(userLikeBo.getLikeType())) {
            NovelInfoVo novelInfoVo = novelInfoService.queryById(userLikeBo.getLikeTypeId());
            if (novelInfoVo == null) {
                return R.fail("点赞的对象ID不对");
            }
            NovelInfoBo novelInfoBo = new NovelInfoBo();
            novelInfoBo.setId(novelInfoVo.getId());
            novelInfoBo.setLikeNum(novelInfoVo.getLikeNum() + 1);
            novelInfoService.updateByBo(novelInfoBo);
        } else if ("3".equals(userLikeBo.getLikeType())) {
            CaricatureInfoVo caricatureInfoVo = caricatureInfoService.queryById(userLikeBo.getLikeTypeId());
            if (caricatureInfoVo == null) {
                return R.fail("点赞的对象ID不对");
            }
            CaricatureInfoBo caricatureInfoBo = new CaricatureInfoBo();
            caricatureInfoBo.setId(caricatureInfoVo.getId());
            caricatureInfoBo.setLikeNum(caricatureInfoVo.getLikeNum() + 1);
            caricatureInfoService.updateByBo(caricatureInfoBo);
        } else {
            VideoInfoVo videoInfoVo = videoInfoService.queryById(userLikeBo.getLikeTypeId());
            if (videoInfoVo == null) {
                return R.fail("点赞的对象ID不对");
            }
            VideoInfoBo videoInfoBo = new VideoInfoBo();
            videoInfoBo.setId(videoInfoVo.getId());
            videoInfoBo.setLikeNum(videoInfoVo.getLikeNum() + 1);
            videoInfoService.updateByBo(videoInfoBo);
        }
        return R.ok();
    }

    /**
     * 新增取消收藏
     * collectionId 收藏ID(网格视频、短视频、小说、漫画、动漫 的id）
     * collectionType 收藏类型（0-网格视频、1-短视频、2-小说、3-漫画、4-动漫）
     */
    @PostMapping("/insertCollection")
    @RepeatSubmit
    public R<Void> insertCollection(@RequestBody JSONObject jsonObject) {
        if (!jsonObject.containsKey("collectionId") || ObjectUtil.isEmpty(jsonObject.get("collectionId"))) {
            return R.fail("收藏ID不能为空！");
        }
        CollectionInfo collectionInfo = new CollectionInfo();
        collectionInfo.setUserId(LoginHelper.getUserId());
        collectionInfo.setCollectionId(jsonObject.getLong("collectionId"));
        collectionInfo.setCollectionType(jsonObject.getStr("collectionType"));
        CollectionInfo collection = collectionService.selectCollection(collectionInfo);
        if (collection != null) {
            collectionService.deleteCollection(collection);

            if ("2".equals(collectionInfo.getCollectionType())) {
                NovelInfoVo novelInfoVo = novelInfoService.queryById(collectionInfo.getCollectionId());
                NovelInfoBo novelInfoBo = new NovelInfoBo();
                novelInfoBo.setId(novelInfoVo.getId());
                novelInfoBo.setCollectNum(novelInfoVo.getLikeNum() - 1);
                novelInfoService.updateByBo(novelInfoBo);
            } else if ("3".equals(collectionInfo.getCollectionType())) {
                CaricatureInfoVo caricatureInfoVo = caricatureInfoService.queryById(collectionInfo.getCollectionId());
                CaricatureInfoBo caricatureInfoBo = new CaricatureInfoBo();
                caricatureInfoBo.setId(caricatureInfoVo.getId());
                caricatureInfoBo.setCollectNum(caricatureInfoVo.getLikeNum() - 1);
                caricatureInfoService.updateByBo(caricatureInfoBo);
            } else {
                VideoInfoVo videoInfoVo = videoInfoService.queryById(collectionInfo.getCollectionId());
                VideoInfoBo videoInfoBo = new VideoInfoBo();
                videoInfoBo.setId(videoInfoVo.getId());
                videoInfoBo.setCollectNum(videoInfoVo.getLikeNum() - 1);
                videoInfoService.updateByBo(videoInfoBo);
            }

            return R.ok();
        }
        collectionService.insertCollection(collectionInfo);
        // 更新各类型的收藏量
        if ("0".equals(jsonObject.getStr("collectionType")) || "1".equals(jsonObject.getStr("collectionType")) || "4".equals(jsonObject.getStr("collectionType"))) {
            VideoInfoVo videoInfoVo = videoInfoService.queryById(collectionInfo.getCollectionId());
            VideoInfoBo videoInfoBo = new VideoInfoBo();
            videoInfoBo.setCollectNum(videoInfoVo.getCollectNum() + 1);
            videoInfoService.updateByBo(videoInfoBo);
        } else if ("2".equals(jsonObject.getStr("collectionType"))) {
            NovelInfoVo novelInfoVo = novelInfoService.queryById(collectionInfo.getCollectionId());
            NovelInfoBo novelInfoBo = new NovelInfoBo();
            novelInfoBo.setCollectNum(novelInfoVo.getCollectNum() + 1);
            novelInfoService.updateByBo(novelInfoBo);
        } else {
            CaricatureInfoVo caricatureInfoVo = caricatureInfoService.queryById(collectionInfo.getCollectionId());
            CaricatureInfoBo caricatureInfoBo = new CaricatureInfoBo();
            caricatureInfoBo.setCollectNum(caricatureInfoVo.getCollectNum() + 1);
            caricatureInfoService.updateByBo(caricatureInfoBo);
        }
        return R.ok();
    }

    /**
     * 新增评论
     * commentId 评论ID(网格视频、短视频、小说、漫画、动漫 的id）
     * content 评论内容
     * commentType 评论类型（0-网格视频、1-短视频、2-小说、3-漫画、4-动漫）
     */
    @PostMapping("/insertComment")
    public R<Void> insertComment(@RequestBody JSONObject params) {
        if (!params.containsKey("commentId") || ObjectUtil.isEmpty(params.getStr("commentId"))) {
            return R.fail("评论ID不能为空！");
        }
        if (!params.containsKey("content") || ObjectUtil.isEmpty(params.getStr("content"))) {
            return R.fail("评论内容不能为空！");
        }
        if (!params.containsKey("commentType") || ObjectUtil.isEmpty(params.getStr("commentType"))) {
            return R.fail("评论类型不能为空！");
        }
        CommentBo commentBo = new CommentBo();
        commentBo.setUserId(LoginHelper.getUserId());
        commentBo.setCommentId(params.getLong("commentId"));
        commentBo.setContent(params.getStr("content"));
        commentBo.setCommentType(params.getStr("commentType"));
        commentBo.setAuditStatus("0");
        commentService.insertByBo(commentBo);
        // 更新各类型的评论量
        if ("0".equals(params.getStr("commentType")) || "1".equals(params.getStr("commentType")) || "4".equals(params.getStr("commentType"))) {
            VideoInfoVo videoInfoVo = videoInfoService.queryById(commentBo.getCommentId());
            VideoInfoBo videoInfoBo = new VideoInfoBo();
            videoInfoBo.setCommentNum(videoInfoVo.getCommentNum() + 1);
            videoInfoService.updateByBo(videoInfoBo);
        } else if ("2".equals(params.getStr("commentType"))) {
            NovelInfoVo novelInfoVo = novelInfoService.queryById(commentBo.getCommentId());
            NovelInfoBo novelInfoBo = new NovelInfoBo();
            novelInfoBo.setReviewNum(novelInfoVo.getReviewNum() + 1);
            novelInfoService.updateByBo(novelInfoBo);
        } else {
            CaricatureInfoVo caricatureInfoVo = caricatureInfoService.queryById(commentBo.getCommentId());
            CaricatureInfoBo caricatureInfoBo = new CaricatureInfoBo();
            caricatureInfoBo.setReviewNum(caricatureInfoVo.getReviewNum() + 1);
            caricatureInfoService.updateByBo(caricatureInfoBo);
        }
        return R.ok();
    }


}
